package com.jianshuge.app.api;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import com.jianshuge.app.AppContext;
import com.jianshuge.app.AppException;
import com.jianshuge.app.R;

import com.jianshuge.app.bean.User;
import com.jianshuge.app.bean.FriendList;

import com.jianshuge.app.bean.BooklistList;
import com.jianshuge.app.bean.BehaviorList;
import com.jianshuge.app.bean.BookshelfList;
import com.jianshuge.app.bean.MyBooklistDetail;
import com.jianshuge.app.bean.MyBookDetail;

import com.jianshuge.app.bean.Notice;
import com.jianshuge.app.bean.URLs;
import com.jianshuge.app.bean.MyResult;
import com.jianshuge.app.bean.Update;
import com.jianshuge.app.bean.User;

import com.jianshuge.app.bean.FriendList;
import com.jianshuge.app.bean.MyInformation;
import com.jianshuge.app.bean.UserInformation;
import com.jianshuge.app.bean.BookItemList;
import com.jianshuge.app.bean.DoubanBook;

import com.jianshuge.app.common.UIHelper;


import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * API客户端接口：用于访问网络数据
 */
public class ApiClient {

	public static final String UTF_8 = "UTF-8";
	public static final String DESC = "descend";
	public static final String ASC = "ascend";
	
	private final static int TIMEOUT_CONNECTION = 20000;
	private final static int TIMEOUT_SOCKET = 20000;
	private final static int RETRY_TIME = 3;

	private static String appCookie;
	private static String appUserAgent;

	public static void cleanCookie() {
		appCookie = "";
	}
	
	private static String getCookie(AppContext appContext) {
		if(appCookie == null || appCookie == "") {
			appCookie = appContext.getProperty("cookie");
		}
		return appCookie;
	}
	
	private static String getUserAgent(AppContext appContext) {
		if(appUserAgent == null || appUserAgent == "") {
			StringBuilder ua = new StringBuilder("jianshuge.com");
			ua.append('/'+appContext.getPackageInfo().versionName+'_'+appContext.getPackageInfo().versionCode);//App版本
			ua.append("/Android");//手机系统平台
			ua.append("/"+android.os.Build.VERSION.RELEASE);//手机系统版本
			ua.append("/"+android.os.Build.MODEL); //手机型号
			ua.append("/"+appContext.getAppId());//客户端唯一标识
			appUserAgent = ua.toString();
		}
		return appUserAgent;
	}
	
	private static HttpClient getHttpClient() {        
        HttpClient httpClient = new HttpClient();
		// 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
		httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        // 设置 默认的超时重试处理策略
		httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
		// 设置 连接超时时间
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT_CONNECTION);
		// 设置 读数据超时时间 
		httpClient.getHttpConnectionManager().getParams().setSoTimeout(TIMEOUT_SOCKET);
		// 设置 字符集
		httpClient.getParams().setContentCharset(UTF_8);
		return httpClient;
	}	
	
	private static GetMethod getHttpGet(String url, String cookie, String userAgent) {
		GetMethod httpGet = new GetMethod(url);
		// 设置 请求超时时间
		httpGet.getParams().setSoTimeout(TIMEOUT_SOCKET);
		httpGet.setRequestHeader("Host", URLs.HOST);
		httpGet.setRequestHeader("Connection","Keep-Alive");
		httpGet.setRequestHeader("Cookie", cookie);
		httpGet.setRequestHeader("User-Agent", userAgent);
		return httpGet;
	}
	
	private static PostMethod getHttpPost(String url, String cookie, String userAgent) {
		PostMethod httpPost = new PostMethod(url);
		// 设置 请求超时时间
		httpPost.getParams().setSoTimeout(TIMEOUT_SOCKET);
		httpPost.setRequestHeader("Host", URLs.HOST);
		httpPost.setRequestHeader("Connection","Keep-Alive");
		httpPost.setRequestHeader("Cookie", cookie);
		httpPost.setRequestHeader("User-Agent", userAgent);
		return httpPost;
	}
	
	private static String _MakeURL(String p_url, Map<String, Object> params) {
		StringBuilder url = new StringBuilder(p_url);
		if(url.indexOf("?")<0)
			url.append('?');

		for(String name : params.keySet()){
			url.append('&');
			url.append(name);
			url.append('=');
			url.append(String.valueOf(params.get(name)));
			//不做URLEncoder处理
			//url.append(URLEncoder.encode(String.valueOf(params.get(name)), UTF_8));
		}

		return url.toString().replace("?&", "?");
	}
	
	/**
	 * get请求URL
	 * @param url
	 * @throws AppException 
	 */
	private static InputStream http_get(AppContext appContext, String url) throws AppException {	
		
		System.out.println("get_url==> "+url);
		
		String cookie = getCookie(appContext);
		String userAgent = getUserAgent(appContext);
		
		HttpClient httpClient = null;
		GetMethod httpGet = null;

		String responseBody = "";
		int time = 0;
		do{
			try 
			{
				httpClient = getHttpClient();
				httpGet = getHttpGet(url, cookie, userAgent);			
				int statusCode = httpClient.executeMethod(httpGet);
				if (statusCode != HttpStatus.SC_OK) {
					throw AppException.http(statusCode);
				}
				
				//responseBody = httpGet.getResponseBodyAsString();
				InputStream resStream = httpGet.getResponseBodyAsStream();
				String inputStr;
				BufferedReader streamReader = new BufferedReader( new InputStreamReader(resStream) ); 
			    StringBuilder responseStrBuilder = new StringBuilder();
			    while ((inputStr = streamReader.readLine()) != null)
			        responseStrBuilder.append(inputStr);
			    responseBody = responseStrBuilder.toString();
			    
				break;	
				
			} catch (HttpException e) {
				time++;
				if(time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {} 
					continue;
				}
				
			// 	发生致命的异常，可能是协议不对或者返回的内容有问题
				e.printStackTrace();
				throw AppException.http(e);
			} catch (IOException e) {
				time++;
				if(time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {} 
					continue;
				}
				
			// 	发生网络异常
				e.printStackTrace();
				throw AppException.network(e);
			} finally {
			
			// 	释放连接
				httpGet.releaseConnection();
				httpClient = null;
			}
		}while(time < RETRY_TIME);
		
		
		responseBody = responseBody.replaceAll("\\p{Cntrl}", "");
		if(responseBody.contains("result") && responseBody.contains("errorCode") && appContext.containsProperty("user.uid")){
			try {
				MyResult res = MyResult.parse(new ByteArrayInputStream(responseBody.getBytes()));	
				if(res.getErrorCode() == 0){
					appContext.Logout();
					appContext.getUnLoginHandler().sendEmptyMessage(1);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}			
		}

	//	System.out.println("XMLDATA=====>"+responseBody);
		return new ByteArrayInputStream(responseBody.getBytes());
	}
	
	/**
	 * 公用post方法
	 * @param url
	 * @param params
	 * @param files
	 * @throws AppException
	 */
	private static InputStream _post(AppContext appContext, String url, Map<String, Object> params, Map<String,File> files) throws AppException {
		
		System.out.println("post_url==> "+url);
		String cookie = getCookie(appContext);
		String userAgent = getUserAgent(appContext);
		
		HttpClient httpClient = null;
		PostMethod httpPost = null;
		
		//post表单参数处理
		int length = (params == null ? 0 : params.size()) + (files == null ? 0 : files.size());
		Part[] parts = new Part[length];
		int i = 0;
        if(params != null)
        for(String name : params.keySet()){
        	parts[i++] = new StringPart(name, String.valueOf(params.get(name)), UTF_8);
        	System.out.println("post_key==> "+name+"    value==>"+String.valueOf(params.get(name)));
        }
        if(files != null)
        for(String file : files.keySet()){
        	try {
				parts[i++] = new FilePart(file, files.get(file));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
        	//System.out.println("post_key_file==> "+file);
        }
		
		String responseBody = "";
		int time = 0;
		do{
			try 
			{
				httpClient = getHttpClient();
				httpPost = getHttpPost(url, cookie, userAgent);	        
		        httpPost.setRequestEntity(new MultipartRequestEntity(parts,httpPost.getParams()));		        
		        int statusCode = httpClient.executeMethod(httpPost);
		        if(statusCode != HttpStatus.SC_OK) 
		        {
		        	throw AppException.http(statusCode);
		        }
		        else if(statusCode == HttpStatus.SC_OK) 
		        {
		            Cookie[] cookies = httpClient.getState().getCookies();
		            String tmpcookies = "";
		            for (Cookie ck : cookies) {
		                tmpcookies += ck.toString()+";";
		            }
		            //保存cookie   
	        		if(appContext != null && tmpcookies != ""){
	        			appContext.setProperty("cookie", tmpcookies);
	        			appCookie = tmpcookies;
	        		}
		        }
		     	responseBody = httpPost.getResponseBodyAsString();
		        //System.out.println("XMLDATA=====>"+responseBody);
		     	break;	     	
			} catch (HttpException e) {
				time++;
				if(time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {} 
					continue;
				}
				// 发生致命的异常，可能是协议不对或者返回的内容有问题
				e.printStackTrace();
				throw AppException.http(e);
			} catch (IOException e) {
				time++;
				if(time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {} 
					continue;
				}
				// 发生网络异常
				e.printStackTrace();
				throw AppException.network(e);
			} finally {
				// 释放连接
				httpPost.releaseConnection();
				httpClient = null;
			}
		}while(time < RETRY_TIME);
        
        responseBody = responseBody.replaceAll("\\p{Cntrl}", "");
		if(responseBody.contains("result") && responseBody.contains("errorCode") && appContext.containsProperty("user.uid")){
			try {
				MyResult res = MyResult.parse(new ByteArrayInputStream(responseBody.getBytes()));	
				if(res.getErrorCode() == 0){
					appContext.Logout();
					appContext.getUnLoginHandler().sendEmptyMessage(1);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}			
		}
        return new ByteArrayInputStream(responseBody.getBytes());
	}
	
	/**
	 * post请求URL
	 * @param url
	 * @param params
	 * @param files
	 * @throws AppException 
	 * @throws IOException 
	 * @throws  
	 */
	private static MyResult http_post(AppContext appContext, String url, Map<String, Object> params, Map<String,File> files) throws AppException, IOException {
        return MyResult.parse(_post(appContext, url, params, files));  
	}	
	
	/**
	 * 获取网络图片
	 * @param url
	 * @return
	 */
	public static Bitmap getNetBitmap(String url) throws AppException {
		
		System.out.println("image_url==> "+url);
		HttpClient httpClient = null;
		GetMethod httpGet = null;
		Bitmap bitmap = null;
		int time = 0;
		do{
			try 
			{
				httpClient = getHttpClient();
				httpGet = getHttpGet(url, null, null);
				int statusCode = httpClient.executeMethod(httpGet);
				if (statusCode != HttpStatus.SC_OK) {
					throw AppException.http(statusCode);
				}
		        InputStream inStream = httpGet.getResponseBodyAsStream();
		        bitmap = BitmapFactory.decodeStream(inStream);
		        inStream.close();
		        break;
			} catch (HttpException e) {
				time++;
				if(time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {} 
					continue;
				}
				// 发生致命的异常，可能是协议不对或者返回的内容有问题
				e.printStackTrace();
				throw AppException.http(e);
			} catch (IOException e) {
				time++;
				if(time < RETRY_TIME) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e1) {} 
					continue;
				}
				// 发生网络异常
				e.printStackTrace();
				throw AppException.network(e);
			} finally {
				// 释放连接
				httpGet.releaseConnection();
				httpClient = null;
			}
		}while(time < RETRY_TIME);
		
		return bitmap;
	}
	
	/**
	 * 检查版本更新
	 * @param url
	 * @return
	 */
	public static Update checkVersion(AppContext appContext) throws AppException {
		try{
			return Update.parse(http_get(appContext, URLs.UPDATE_VERSION));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	public static User login_auth(AppContext appContext, String access_token, String login_type ) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("c", "api");
		params.put("a", "login");
		params.put("access_token", access_token);
		params.put("login_type", login_type);
		
		String loginurl = URLs.USER_LOGIN_AUTH;
		if(appContext.isHttpsLogin()){
			loginurl = URLs.LOGIN_VALIDATE_HTTPS;
		}
		
		try{
			return User.parse(_post(appContext, loginurl, params, null));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 登录， 自动处理cookie
	 * @param url
	 * @param username
	 * @param pwd
	 * @return
	 * @throws AppException
	 */
	public static User login(AppContext appContext, String username, String pwd) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("username", username);
		params.put("pwd", pwd);
		params.put("keep_login", 1);
				
		String loginurl = URLs.LOGIN_VALIDATE_HTTP;
		if(appContext.isHttpsLogin()){
			loginurl = URLs.LOGIN_VALIDATE_HTTPS;
		}
		
		try{
			return User.parse(_post(appContext, loginurl, params, null));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 我的个人资料
	 * @param appContext
	 * @param uid
	 * @return
	 * @throws AppException
	 */
	public static MyInformation myInformation(AppContext appContext, int tuid) throws AppException {
		
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("suid", appContext.getLoginUid());
		params.put("tuid", tuid);
		try{
			return MyInformation.parse( _post(appContext, URLs.SHOW_MY_PROFILE, params, null) );		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 更新用户头像
	 * @param appContext
	 * @param uid 当前用户uid
	 * @param portrait 新上传的头像
	 * @return
	 * @throws AppException
	 */
	public static MyResult updatePortrait(AppContext appContext, int uid, File portrait) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		
		Map<String, File> files = new HashMap<String, File>();
		files.put("portrait", portrait);
				
		try{
			return http_post(appContext, URLs.PORTRAIT_UPDATE, params, files);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 获取用户信息个人专页（包含该用户的动态信息以及个人信息）
	 * @param uid 自己的uid
	 * @param hisuid 被查看用户的uid
	 * @param hisname 被查看用户的用户名
	 * @param pageIndex 页面索引
	 * @param pageSize 每页读取的动态个数
	 * @return
	 * @throws AppException
	 */
	public static User getUserInfo(AppContext appContext, int tuid) throws AppException {		
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("suid", appContext.getLoginUid());
		params.put("tuid", tuid);
		try{
			return User.parse( _post(appContext, URLs.USER_INFORMATION, params, null) );		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 更新用户之间关系（加关注、取消关注）
	 * @param uid 自己的uid
	 * @param hisuid 对方用户的uid
	 * @param newrelation 0:取消对他的关注 1:关注他
	 * @return
	 * @throws AppException
	 */
	public static MyResult updateRelation(AppContext appContext, int uid, int hisuid, int newrelation) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("hisuid", hisuid);
		params.put("newrelation", newrelation);
				
		try{
			return MyResult.parse(_post(appContext, URLs.USER_UPDATERELATION, params, null));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 获取用户通知信息
	 * @param uid
	 * @return
	 * @throws AppException
	 */
	public static Notice getUserNotice(AppContext appContext, int uid) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
				
		try{		
			return Notice.parse(_post(appContext, URLs.USER_NOTICE, params, null));			
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 清空通知消息
	 * @param uid
	 * @param type 1:@我的信息 2:未读消息 3:评论个数 4:新粉丝个数
	 * @return
	 * @throws AppException
	 */
	public static MyResult noticeClear(AppContext appContext, int uid, int type) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("type", type);
				
		try{
			
			return MyResult.parse(_post(appContext, URLs.NOTICE_CLEAR, params, null));					
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 用户粉丝、关注人列表
	 * @param uid
	 * @param relation 0:显示自己的粉丝 1:显示自己的关注者
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static FriendList getFriendList(AppContext appContext, final int uid, final int relation, final int pageIndex, final int pageSize) throws AppException {
		
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		
		if (relation == 0)
			params.put("ft", "follower");
		if (relation == 1)
			params.put("ft", "fans");

		params.put("pageIndex", pageIndex);
		params.put("pageSize", pageSize);	

		try{
			return FriendList.parse(_post(appContext, URLs.FRIENDS_LIST, params, null));
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 获取书单列表
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public static BooklistList getBooklistList(AppContext appContext, final int catalog, final int pageIndex, final int pageSize, final int uid ) throws AppException {

		String NewUrl = "";
		if (catalog == 1)
			NewUrl = URLs.HOT_BOOKLIST_LIST ;
		if (catalog == 2)
			NewUrl = URLs.ZERO_BOOKLIST_LIST ;
		if (catalog == 3)
			NewUrl = URLs.USER_FOLLOWED_BOOKLIST_LIST ;
		if (catalog == 4)
			NewUrl = URLs.USER_CREATED_BOOKLIST_LIST ;
		if (catalog == 5)
			NewUrl = URLs.USER_PART_BOOKLIST_LIST ;

		Map<String,Object> params = new HashMap<String,Object>();	
		if( catalog == 3 || catalog == 4 || catalog == 5 ) {
			params.put("uid", uid);
		}		
		params.put("pageIndex", pageIndex);
		params.put("pageSize", pageSize);	

		try{
			return BooklistList.parse(_post(appContext, NewUrl, params, null));
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 获取最新动态 / 用户最新动态
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public static BehaviorList getBehaviorList(AppContext appContext, final int pageIndex, final int pageSize, final int uid ) throws AppException {		
		Map<String,Object> params = new HashMap<String,Object>();	
		if( uid == -1 ) {
			params.put("pageIndex", pageIndex);
			params.put("pageSize", pageSize);	
		} else {
			params.put("uid", uid);
			params.put("pageIndex", pageIndex);
			params.put("pageSize", pageSize);	
		}
		
		try{
		
			if( uid == -1 )
				return BehaviorList.parse(_post(appContext, URLs.RECENT_TREND_LIST, params, null));
			else
				return BehaviorList.parse(_post(appContext, URLs.USER_TIMELINE_LIST, params, null));
			
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	public static BehaviorList getUserBehavior(AppContext appContext, final int pageIndex, final int pageSize, final int uid ) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("pageIndex", pageIndex);
		params.put("pageSize", pageSize);		

		try{
			return BehaviorList.parse(_post(appContext, URLs.USER_BEHAVIOR_LIST, params, null));	
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 获取用户藏书架
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public static BookshelfList getBookshelfList(AppContext appContext, final int pageIndex, final int pageSize, final int uid ) throws AppException {
	
	//	String NewUrl = URLs.USER_BOOKSHELF_LIST + "/" + uid + "-" + pageIndex;
		
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("pageIndex", pageIndex);
		params.put("pageSize", pageSize);		

		try{
			int bookshelf_start = (pageIndex - 1) * 10 + 1;
			return BookshelfList.parse(_post(appContext, URLs.USER_BOOKSHELF_LIST, params, null), bookshelf_start);
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	
	/**
	 * 获取用户藏书架
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public static BookshelfList getNewBook(AppContext appContext, final int pageIndex, final int pageSize, final int uid ) throws AppException {
	
	//	String NewUrl = URLs.NEW_BOOK_LIST + "/" + pageIndex;
		
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("pageIndex", pageIndex);
		params.put("pageSize", pageSize);		

		try{
			int bookshelf_start = (pageIndex - 1) * 10 + 1;
			return BookshelfList.parse(_post(appContext, URLs.NEW_BOOK_LIST, params, null), bookshelf_start);
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	public static BehaviorList getMessageList(AppContext appContext, final int pageIndex, final int pageSize, final int uid ) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("pageIndex", pageIndex);
		params.put("pageSize", pageSize);		
	
		try{
			return BehaviorList.parse(_post(appContext, URLs.NEW_NOTIFICATION_LIST, params, null));
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 删除留言
	 * @param uid 登录用户uid
	 * @param friendid 留言者id
	 * @return
	 * @throws AppException
	 */
	public static MyResult delMessage(AppContext appContext, int uid ) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		
		try{
			//return http_post(appContext, URLs.MESSAGE_DELETE, params, null);	
			
			String responseBody = "HELLO GNU";
			InputStream inputStream = new ByteArrayInputStream(responseBody.getBytes());
			return MyResult.parse(inputStream);
			
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}

	/**
	 * 获取书单详情
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public static MyBooklistDetail getBooklistDetail(AppContext appContext, final int uid, final int booklist_id ) throws AppException {

	//	String NewUrl = URLs.BOOKLIST_DETAIL + "/" + uid + "-" + booklist_id ;

		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("blid", booklist_id);
		try{
		//	return MyBooklistDetail.parse(http_get(appContext, NewUrl));	
			return MyBooklistDetail.parse(_post(appContext, URLs.BOOKLIST_DETAIL, params, null));
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	public static MyBookDetail getBookDetail(AppContext appContext, final int uid, final int book_id ) throws AppException {

		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("bid", book_id);
		try{
			return MyBookDetail.parse(_post(appContext, URLs.BOOK_DETAIL, params, null));
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	
	/**
	 * 获取搜索列表
	 * @param catalog 
	 * @param content 搜索的内容
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static BooklistList SearchBooklist(AppContext appContext, int catalog, String content, int pageIndex, int pageSize) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("catalog", catalog);
		params.put("content", content);
		params.put("pageIndex", pageIndex);
		params.put("pageSize", pageSize);

		try{
				return BooklistList.parse(_post(appContext, URLs.SEARCH_BOOKLIST_LIST, params, null));
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 获取搜索列表
	 * @param catalog 
	 * @param content 搜索的内容
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 * @throws AppException
	 */
	public static BookItemList SearchBook(AppContext appContext, int catalog, String content, int pageIndex, int pageSize) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("catalog", catalog);
		params.put("content", content);
		params.put("pageIndex", pageIndex);
		params.put("pageSize", pageSize);

		try{
				//return BookItemList.parse(_post(appContext, URLs.SEARCH_BOOK_LIST, params, null));
				return BookItemList.parse(_post(appContext, URLs.SEARCH_DOUBAN_BOOK_LIST, params, null));
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	public static BookItemList SearchDouban(AppContext appContext, int catalog, String content, int pageIndex, int pageSize) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("catalog", catalog);
		params.put("content", content);
		params.put("pageIndex", pageIndex);
		params.put("pageSize", pageSize);

		try{
				return BookItemList.parse(_post(appContext, URLs.SEARCH_DOUBAN_BOOK_LIST, params, null));
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 通过Tag获取书单列表
	 * @param url
	 * @param catalog
	 * @param pageIndex
	 * @return
	 * @throws AppException
	 */
	public static BooklistList getBooklistListByTag(AppContext appContext, final String tag, final int pageIndex, final int pageSize) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("tag", tag);
		params.put("pageIndex", pageIndex);
		params.put("pageSize", pageSize);		

		try{
			return BooklistList.parse(_post(appContext, URLs.TAG_BOOKLIST_LIST, params, null));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 用户投票给书籍
	 * @param uid 用户UID
	 * @return
	 * @throws AppException
	 */
	public static MyResult addVote(AppContext appContext, int uid, int booklistitem_id, 
							int booklist_id, int book_id, int contributor_id) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		
		params.put("booklistitem_id", booklistitem_id);
		params.put("booklist_id", booklist_id);
		params.put("book_id", book_id);
		params.put("contributor_id", contributor_id);
		
		params.put("vote_type", 0);
		params.put("vote", 1);

		try{
			return http_post(appContext, URLs.VOTE_ADD, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 用户取消投票给书籍
	 * @param uid 用户UID
	 * @return
	 * @throws AppException
	 */
	public static MyResult delVote(AppContext appContext, int uid, int booklistitem_id, 
				int booklist_id, int book_id, int contributor_id) throws AppException {

		
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		
		params.put("booklistitem_id", booklistitem_id);
		params.put("booklist_id", booklist_id);
		params.put("book_id", book_id);
		params.put("contributor_id", contributor_id);
		
		params.put("vote_type", 1);
		params.put("vote", -1);
		

		try{
			return http_post(appContext, URLs.VOTE_DELETE, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}

	/**
	 * 用户添加收藏
	 * @param uid 用户UID
	 * @return
	 * @throws AppException
	 */
	public static MyResult addFavorite(AppContext appContext, int uid, int book_id) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("book_id", book_id);
		try{
			return http_post(appContext, URLs.FAVORITE_ADD, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	

	/**
	 * 用户删除收藏
	 * @param uid 用户UID
	 * @return
	 * @throws AppException
	 */
	public static MyResult delFavorite(AppContext appContext, int uid, int book_id) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("book_id", book_id);

		try{
			return http_post(appContext, URLs.FAVORITE_DELETE, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	public static DoubanBook getDoubanBookByIsbn(AppContext appContext,  final String isbn ) throws AppException {

		String NewUrl = URLs.GET_DOUBAN_BOOK_BY_ISBN + "/" + isbn;
		
		try{
			return DoubanBook.parse(http_get(appContext, NewUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	public static DoubanBook getDoubanBookBySubject(AppContext appContext,  final String subject_id ) throws AppException {

		String NewUrl = URLs.GET_DOUBAN_BOOK_BY_SUBJECT + "/" + subject_id;
		
		try{
			return DoubanBook.parse(http_get(appContext, NewUrl));		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	
	public static MyResult saveDoubanBook(AppContext appContext,  final String subject_id ) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("subject_id", subject_id);
		
		try{	
			return http_post(appContext, URLs.SAVE_DOUBAN_BOOK, params, null);	
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	public static MyResult scanFavorite(AppContext appContext, int uid, String subject_id) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("subject_id", subject_id);
		try{
			return http_post(appContext, URLs.SCAN_FAVORITE, params, null);	
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	public static MyResult addBookResult(AppContext appContext,  final int uid, final int booklist_id, final int book_id, final String recomment ) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("blid", booklist_id);
		params.put("bid", book_id);
		params.put("recomment", recomment);		
		try{
			return http_post(appContext, URLs.ADD_TO_BOOKLIST, params, null);	
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	public static MyResult updateRecomment(AppContext appContext,  final int uid, final int booklist_id, final int book_id, final String recomment ) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("blid", booklist_id);
		params.put("bid", book_id);
		params.put("recomment", recomment);		
		try{
			return http_post(appContext, URLs.UPDATE_RECOMMENT, params, null);	
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 关注书单
	 * @param uid 用户UID
	 * @return
	 * @throws AppException
	 */
    public static MyResult followBooklist(AppContext appContext, int uid, int booklist_id) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("blid", booklist_id);

		try{
			return http_post(appContext, URLs.FOLLOW_BOOKLIST, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 取消关注书单
	 * @param uid 用户UID
	 * @return
	 * @throws AppException
	 */
	public static MyResult unfollowBooklist(AppContext appContext, int uid, int booklist_id) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("blid", booklist_id);

		try{
			return http_post(appContext, URLs.UNFOLLOW_BOOKLIST, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 用户关注用户
	 * @param uid 用户UID
	 * @return
	 * @throws AppException
	 */
	public static MyResult followUser(AppContext appContext, int suid, int tuid) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("suid", suid);
		params.put("tuid", tuid);

		try{
			return http_post(appContext, URLs.FOLLOW_USER, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 取消关注用户
	 * @param uid 用户UID
	 * @return
	 * @throws AppException
	 */	
	public static MyResult unfollowUser(AppContext appContext, int suid, int tuid) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("suid", suid);
		params.put("tuid", tuid);

		try{
			return http_post(appContext, URLs.UNFOLLOW_USER, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	public static MyResult pubBooklist(AppContext appContext, int uid, String title, String content) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("title", title);
		params.put("content", content);
		try{
			return http_post(appContext, URLs.BOOKLIST_PUB, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	
	public static MyResult updateBooklist(AppContext appContext, int uid, int booklist_id, String title, String content) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("blid", booklist_id);
		params.put("title", title);
		params.put("desc", content);
		try{
			return http_post(appContext, URLs.BOOKLIST_UPDATE, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}

	/**
	 * 发表评论
	 * @param uid 用户uid
	 * @param content 发表评论的内容
	 * @return
	 * @throws AppException
	 */
	public static MyResult pubComment(AppContext appContext,int uid, int item_id, String content, int catalog) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("item_id", item_id);
		params.put("content", content);
		params.put("type", catalog);
		
		try{
			return http_post(appContext, URLs.COMMENT_PUB, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}

	/**
	 * 
	 * @param id 表示被评论的某条新闻，帖子，动弹的id 或者某条消息的 friendid 
	 * @param catalog 表示该评论所属什么类型：1新闻  2帖子  3动弹  4动态
	 * @param replyid 表示被回复的单个评论id
	 * @param authorid 表示该评论的原始作者id
	 * @param uid 用户uid 一般都是当前登录用户uid
	 * @param content 发表评论的内容
	 * @return
	 * @throws AppException
	 */
	public static MyResult replyComment(AppContext appContext, int id, int catalog, int replyid, int authorid, int uid, String content) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("catalog", catalog);
		params.put("id", id);
		params.put("uid", uid);
		params.put("content", content);
		params.put("replyid", replyid);
		params.put("authorid", authorid);
		
		try{
			return http_post(appContext, URLs.COMMENT_REPLY, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	public static MyResult pubFeedback(AppContext appContext, int uid, String content) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("content", content);
		
		try{
			return http_post(appContext, URLs.FEEDBACK_PUB, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	/**
	 * 删除评论
	 * @param uid 表示评论用户
	 * @param rid 表示该评论所属什么类型：0.书单  1.书单条目
	 * @param item_id 表示被评论对应的书单条目id
	 * @return
	 * @throws AppException
	 */
	public static MyResult delComment(AppContext appContext, int uid, int rid, int item_id) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("uid", uid);
		params.put("rid", rid);
		params.put("item_id", item_id);

		try{
			return http_post(appContext, URLs.COMMENT_DELETE, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
	public static MyResult getDoubanBookComment(AppContext appContext, String comment_uri) throws AppException {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("com_uri", comment_uri);
		try{
			return http_post(appContext, URLs.GET_DOUBAN_COMMENT, params, null);		
		}catch(Exception e){
			if(e instanceof AppException)
				throw (AppException)e;
			throw AppException.network(e);
		}
	}
	
}